package com.citycloud.ccuap.tc.oauth2.config.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.citycloud.ccuap.tc.common.result.ResultCodeEnum;
import com.citycloud.ccuap.tc.common.result.ResultObject;
import com.fasterxml.jackson.databind.ObjectMapper;


@Component
public class CustomerAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        response.setContentType("application/json; charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();

        String errorMsg = "系统异常！";
        if (e instanceof BadCredentialsException) {
            errorMsg = "用户名/密码错误，请重新输入！";
            response.getWriter().print(mapper.writeValueAsString(ResultObject.getInstance().error(ResultCodeEnum.SUCCESSFUL_MSG.getCode(), errorMsg)));
        } else if (e instanceof UsernameNotFoundException) {
            errorMsg = "用户名/密码错误，请重新输入！";
            response.getWriter().print(mapper.writeValueAsString(ResultObject.getInstance().error(ResultCodeEnum.SUCCESSFUL_MSG.getCode(), errorMsg)));
        } else if (e instanceof DisabledException) {
            errorMsg = "该用户已被停用！";
            response.getWriter().print(mapper.writeValueAsString(ResultObject.getInstance().error(ResultCodeEnum.SUCCESSFUL_MSG.getCode(), errorMsg)));
        } else {
            response.getWriter().print(mapper.writeValueAsString(ResultObject.getInstance().error(ResultCodeEnum.ERROR.getCode(), errorMsg)));
        }
    }
}
